<template>
  <div class="disaster-management">
    <!-- 功能切换 -->
    <div class="function-tabs">
      <a-radio-group v-model:value="activeTab" button-style="solid" size="large">
        <a-radio-button value="events">灾害事件</a-radio-button>
        <a-radio-button value="monitor">监控预警</a-radio-button>
        <a-radio-button value="response">应急响应</a-radio-button>
        <a-radio-button value="analysis">影响分析</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 灾害事件 -->
    <div v-if="activeTab === 'events'" class="events-section">
      <a-card title="自然灾害事件管理" class="events-card">
        <template #extra>
          <a-space>
            <a-select v-model:value="disasterFilter" placeholder="灾害类型" style="width: 120px">
              <a-select-option value="all">全部类型</a-select-option>
              <a-select-option value="earthquake">地震</a-select-option>
              <a-select-option value="flood">洪水</a-select-option>
              <a-select-option value="typhoon">台风</a-select-option>
              <a-select-option value="drought">干旱</a-select-option>
              <a-select-option value="landslide">山体滑坡</a-select-option>
              <a-select-option value="fire">山火</a-select-option>
            </a-select>
            <a-button type="primary" @click="addDisaster">新增事件</a-button>
          </a-space>
        </template>

        <a-table :columns="disasterColumns" :data-source="filteredDisasters" :loading="loading" row-key="id">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'disaster'">
              <div>
                <a-tag :color="getDisasterColor(record.disasterType)">
                  {{ getDisasterName(record.disasterType) }}
                </a-tag>
                <div style="margin-top: 4px; font-size: 12px; color: #999">
                  {{ record.location }}
                </div>
              </div>
            </template>

            <template v-else-if="column.key === 'severity'">
              <a-tag :color="getSeverityColor(record.severity)">
                {{ getSeverityText(record.severity) }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'impact'">
              <div>
                <div>死亡：{{ record.casualties?.deaths || 0 }}人</div>
                <div>受伤：{{ record.casualties?.injured || 0 }}人</div>
                <div>失踪：{{ record.casualties?.missing || 0 }}人</div>
              </div>
            </template>

            <template v-else-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="viewDetail(record)">详情</a-button>
                <a-button type="link" size="small" @click="editDisaster(record)">编辑</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 监控预警 -->
    <div v-if="activeTab === 'monitor'" class="monitor-section">
      <a-row :gutter="[24, 24]">
        <a-col :xs="24" :lg="12">
          <a-card title="风险监控" class="monitor-card">
            <div class="risk-level-grid">
              <div class="risk-item high">
                <div class="risk-icon">🔴</div>
                <div class="risk-info">
                  <div class="risk-title">高风险区域</div>
                  <div class="risk-count">{{ highRiskAreas }}</div>
                </div>
              </div>
              <div class="risk-item medium">
                <div class="risk-icon">🟡</div>
                <div class="risk-info">
                  <div class="risk-title">中风险区域</div>
                  <div class="risk-count">{{ mediumRiskAreas }}</div>
                </div>
              </div>
              <div class="risk-item low">
                <div class="risk-icon">🟢</div>
                <div class="risk-info">
                  <div class="risk-title">低风险区域</div>
                  <div class="risk-count">{{ lowRiskAreas }}</div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :lg="12">
          <a-card title="预警信息" class="alert-card">
            <div class="alert-list">
              <div v-for="alert in currentAlerts" :key="alert.id" class="alert-item" :class="alert.level">
                <div class="alert-icon">
                  <ExclamationCircleOutlined v-if="alert.level === 'urgent'" />
                  <WarningOutlined v-else />
                </div>
                <div class="alert-content">
                  <div class="alert-title">{{ alert.title }}</div>
                  <div class="alert-desc">{{ alert.description }}</div>
                  <div class="alert-time">{{ formatTime(alert.time) }}</div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 应急响应 -->
    <div v-if="activeTab === 'response'" class="response-section">
      <a-card title="应急响应管理" class="response-card">
        <div class="response-plan">
          <h3>应急预案</h3>
          <a-steps :current="responseStep" direction="vertical">
            <a-step title="预警发布" description="及时发布灾害预警信息" />
            <a-step title="人员疏散" description="组织危险区域人员疏散" />
            <a-step title="救援部署" description="调配救援力量和物资" />
            <a-step title="灾后处理" description="开展救灾和恢复工作" />
          </a-steps>

          <div class="response-actions">
            <a-button type="primary" @click="nextStep" :disabled="responseStep >= 3"> 下一步骤 </a-button>
            <a-button @click="resetResponse" style="margin-left: 8px"> 重置预案 </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 影响分析 -->
    <div v-if="activeTab === 'analysis'" class="analysis-section">
      <a-row :gutter="[24, 24]">
        <a-col :xs="24" :lg="12">
          <a-card title="灾害影响统计" class="stats-card">
            <div ref="impactChart" style="width: 100%; height: 300px"></div>
          </a-card>
        </a-col>

        <a-col :xs="24" :lg="12">
          <a-card title="经济损失评估" class="economic-card">
            <div class="economic-stats">
              <div class="stat-item">
                <div class="stat-label">直接经济损失</div>
                <div class="stat-value">{{ directLoss }}万元</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">间接经济损失</div>
                <div class="stat-value">{{ indirectLoss }}万元</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">总损失</div>
                <div class="stat-value total">{{ totalLoss }}万元</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ExclamationCircleOutlined, WarningOutlined } from '@ant-design/icons-vue'
import { useLifeDeathStore } from '@/stores/lifeDeath'

// Store
const lifeDeathStore = useLifeDeathStore()

// 响应式数据
const activeTab = ref('events')
const disasterFilter = ref('all')
const responseStep = ref(0)

// Chart refs
const impactChart = ref(null)

// 表格列定义
const disasterColumns = [
  { title: '灾害类型', key: 'disaster', width: 150 },
  { title: '发生时间', dataIndex: 'startTime', key: 'startTime', width: 120 },
  { title: '严重程度', key: 'severity', width: 100 },
  { title: '伤亡情况', key: 'impact', width: 120 },
  { title: '影响范围', dataIndex: 'affectedArea', key: 'affectedArea', width: 100 },
  { title: '操作', key: 'actions', width: 120, fixed: 'right' }
]

// 计算属性
const loading = computed(() => lifeDeathStore.loading)

const filteredDisasters = computed(() => {
  let disasters = lifeDeathStore.specialCases.filter((c) => c.caseType === 'disaster')

  console.log('所有特殊情况记录:', lifeDeathStore.specialCases.length)
  console.log('灾害类型记录:', disasters.length)
  console.log('第一个灾害记录:', disasters[0])

  if (disasterFilter.value !== 'all') {
    disasters = disasters.filter((d) => d.disasterType === disasterFilter.value)
  }

  return disasters
})

const highRiskAreas = computed(() => Math.floor(Math.random() * 5) + 2)
const mediumRiskAreas = computed(() => Math.floor(Math.random() * 10) + 5)
const lowRiskAreas = computed(() => Math.floor(Math.random() * 20) + 10)

const currentAlerts = computed(() => [
  {
    id: 1,
    level: 'urgent',
    title: '台风预警',
    description: '预计未来24小时内可能有强台风影响',
    time: new Date().toISOString()
  },
  {
    id: 2,
    level: 'warning',
    title: '洪水预警',
    description: '河流水位持续上涨，需要关注',
    time: new Date(Date.now() - 3600000).toISOString()
  }
])

const directLoss = computed(() => Math.floor(Math.random() * 5000) + 1000)
const indirectLoss = computed(() => Math.floor(Math.random() * 3000) + 500)
const totalLoss = computed(() => directLoss.value + indirectLoss.value)

// 方法
const addDisaster = () => {
  message.info('新增灾害事件功能开发中...')
}

const viewDetail = (record) => {
  message.info(`查看 ${record.name} 的详细信息`)
}

const editDisaster = (record) => {
  message.info(`编辑 ${record.name} 的信息`)
}

const nextStep = () => {
  if (responseStep.value < 3) {
    responseStep.value++
    message.success(`已进入第${responseStep.value + 1}步骤`)
  }
}

const resetResponse = () => {
  responseStep.value = 0
  message.info('应急预案已重置')
}

// 绘制图表
const drawImpactChart = () => {
  console.log('开始绘制灾害影响统计图')

  if (!impactChart.value) {
    console.log('灾害影响图表容器不存在')
    return
  }

  try {
    // 从store获取灾害事件数据
    const disasterEvents = lifeDeathStore.specialCases.filter((c) => c.caseType === 'disaster')
    console.log('获取到灾害事件数据:', disasterEvents.length, '条')

    // 定义灾害类型映射
    const disasterTypeMap = {
      earthquake: '地震',
      flood: '洪水',
      typhoon: '台风',
      drought: '干旱',
      landslide: '山体滑坡',
      fire: '山火'
    }

    const disasterTypes = Object.values(disasterTypeMap)

    // 统计各类型灾害的死亡人数和受影响人数
    const deathCounts = disasterTypes.map((typeName) => {
      const typeKey = Object.keys(disasterTypeMap).find((key) => disasterTypeMap[key] === typeName)
      const eventsOfType = disasterEvents.filter((e) => e.disasterType === typeKey)
      return eventsOfType.reduce((sum, event) => sum + (event.casualties?.deaths || 0), 0)
    })

    const affectedCounts = disasterTypes.map((typeName) => {
      const typeKey = Object.keys(disasterTypeMap).find((key) => disasterTypeMap[key] === typeName)
      const eventsOfType = disasterEvents.filter((e) => e.disasterType === typeKey)
      return eventsOfType.reduce((sum, event) => sum + (event.estimatedVictims || 0), 0)
    })

    console.log('灾害类型:', disasterTypes)
    console.log('死亡统计:', deathCounts)
    console.log('受影响统计:', affectedCounts)

    // 初始化ECharts实例
    const chart = echarts.init(impactChart.value, 'dark')

    // 配置图表选项
    const option = {
      backgroundColor: 'rgba(0, 0, 0, 0)',
      title: {
        text: '灾害影响统计',
        left: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#1890ff',
        textStyle: {
          color: '#ffffff'
        },
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        },
        formatter: function (params) {
          let result = params[0].name + '<br/>'
          params.forEach((param) => {
            result += param.marker + param.seriesName + ': ' + param.value + (param.seriesName === '死亡人数' ? '人' : '人') + '<br/>'
          })
          return result
        }
      },
      legend: {
        data: ['死亡人数', '受影响人数'],
        textStyle: {
          color: '#ffffff'
        },
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: disasterTypes,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          rotate: 15
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '死亡人数',
          position: 'left',
          nameTextStyle: {
            color: 'rgba(255, 255, 255, 0.8)'
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.5)'
            }
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.8)'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        {
          type: 'value',
          name: '受影响人数',
          position: 'right',
          nameTextStyle: {
            color: 'rgba(255, 255, 255, 0.8)'
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.5)'
            }
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.8)'
          }
        }
      ],
      series: [
        {
          name: '死亡人数',
          type: 'bar',
          yAxisIndex: 0,
          data: deathCounts,
          itemStyle: {
            borderRadius: [4, 4, 0, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#ff4d4f' },
              { offset: 1, color: '#ff7875' }
            ])
          },
          label: {
            show: true,
            position: 'top',
            color: '#ffffff',
            fontSize: 10
          }
        },
        {
          name: '受影响人数',
          type: 'line',
          yAxisIndex: 1,
          data: affectedCounts,
          lineStyle: {
            color: '#52c41a',
            width: 3
          },
          itemStyle: {
            color: '#52c41a',
            borderColor: '#ffffff',
            borderWidth: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(82, 196, 26, 0.3)' },
              { offset: 1, color: 'rgba(82, 196, 26, 0.05)' }
            ])
          },
          label: {
            show: false
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    window.addEventListener('resize', () => {
      chart.resize()
    })

    console.log('灾害影响统计图绘制完成')
  } catch (error) {
    console.error('绘制灾害影响统计图时出错:', error)
  }
}

// 工具方法
const getDisasterColor = (type) => {
  const colors = {
    earthquake: 'red',
    flood: 'blue',
    typhoon: 'purple',
    drought: 'orange',
    landslide: 'volcano',
    fire: 'magenta'
  }
  return colors[type] || 'default'
}

const getDisasterName = (type) => {
  const names = {
    earthquake: '地震',
    flood: '洪水',
    typhoon: '台风',
    drought: '干旱',
    landslide: '山体滑坡',
    fire: '山火'
  }
  return names[type] || type
}

const getSeverityColor = (severity) => {
  const colors = {
    low: 'green',
    medium: 'orange',
    high: 'red',
    critical: 'volcano'
  }
  return colors[severity] || 'default'
}

const getSeverityText = (severity) => {
  const texts = {
    low: '轻微',
    medium: '一般',
    high: '严重',
    critical: '重大'
  }
  return texts[severity] || severity
}

const formatTime = (timeString) => {
  return dayjs(timeString).format('MM-DD HH:mm')
}

// 生命周期
onMounted(() => {
  console.log('DisasterManagement组件挂载')
  // 确保数据已加载
  lifeDeathStore.fetchLifeRecords().then(() => {
    console.log('数据加载完成后，specialCases数量:', lifeDeathStore.specialCases.length)
    console.log(
      '灾害类型数据:',
      lifeDeathStore.specialCases.filter((c) => c.caseType === 'disaster')
    )
  })

  nextTick(() => {
    drawImpactChart()
  })
})

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'analysis') {
    nextTick(() => {
      drawImpactChart()
    })
  }
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.disaster-management {
  .function-tabs {
    margin-bottom: 24px;
    text-align: center;
  }

  .risk-level-grid {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .risk-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid $border-color;

      .risk-icon {
        font-size: 32px;
        margin-right: 16px;
      }

      .risk-info {
        .risk-title {
          font-weight: 500;
          color: $text-primary;
          margin-bottom: 4px;
        }

        .risk-count {
          font-size: 24px;
          font-weight: bold;
          color: $text-primary;
        }
      }

      &.high {
        border-left: 4px solid #f5222d;
      }

      &.medium {
        border-left: 4px solid #faad14;
      }

      &.low {
        border-left: 4px solid #52c41a;
      }
    }
  }

  .alert-list {
    .alert-item {
      display: flex;
      align-items: center;
      padding: 12px;
      margin-bottom: 12px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid $border-color;
      border-radius: 8px;

      .alert-icon {
        font-size: 20px;
        margin-right: 12px;
      }

      .alert-content {
        .alert-title {
          font-weight: 500;
          color: $text-primary;
          margin-bottom: 4px;
        }

        .alert-desc {
          font-size: 12px;
          color: $text-secondary;
          margin-bottom: 4px;
        }

        .alert-time {
          font-size: 11px;
          color: $text-tertiary;
        }
      }

      &.urgent {
        border-left: 4px solid #f5222d;

        .alert-icon {
          color: #f5222d;
        }
      }

      &.warning {
        border-left: 4px solid #faad14;

        .alert-icon {
          color: #faad14;
        }
      }
    }
  }

  .response-plan {
    h3 {
      color: $text-primary;
      margin-bottom: 24px;
    }

    .response-actions {
      margin-top: 32px;
    }
  }

  .economic-stats {
    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid $border-color;

      &:last-child {
        border-bottom: none;
      }

      .stat-label {
        color: $text-secondary;
      }

      .stat-value {
        font-weight: bold;
        color: $text-primary;

        &.total {
          color: #f5222d;
          font-size: 18px;
        }
      }
    }
  }
}
</style>
